package cloudContact.servlet;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.mybeans.factory.RollbackException;

import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthException;
import com.google.gdata.util.ServiceException;

import cloudContact.GoogleConstant;
import cloudContact.MyDAOException;
import cloudContact.SecurityManager;
import cloudContact.DAO.GoogleContact;
import cloudContact.DAO.GoogleContactDAO;
import cloudContact.DAO.User;
import cloudContact.DAO.UserDAO;

/**
 * Servlet implementation class LoadImage
 */
@WebServlet("/GoogleLoadImage")
public class GoogleLoadImage extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GoogleLoadImage() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		System.out.println("Start GoogleLoadImage...");

		try {

			if (!SecurityManager.CheckAuthorization(request)) {
				System.out.println("Error: User is not authorized.");
				return;
			}

			// Validate ID parameter
			if (request.getParameter("id") == null
					|| request.getParameter("id").toString().equals("")) {
				System.out.println("Error: Missing ID parameter.");
				return;
			}

			String id = request.getParameter("id").toString();

			// Reverse sanitization
			id = id.replaceAll("\\\\/", "/").replaceAll("@", "%40");

			// Retrieve stored google auth token.
			HttpSession session = request.getSession();

			User user = null;
			try {
				user = UserDAO.getInstance().lookup(
						session.getAttribute("userId").toString());
			} catch (RollbackException e) {
				e.printStackTrace();
			} catch (MyDAOException e) {
				e.printStackTrace();
			}

			if (user == null) {
				System.out.println("Error: User not found.");
				return;
			}

			GoogleOAuthParameters oauthParameters = GoogleConstant
					.getGoogleOAuthParameters(user.getGMailAccessToken(),
							user.getGMailAuthSecrete(), user.getUserId());
			GoogleContactDAO gContactDAO = GoogleContactDAO
					.getInstanceForSession(session.getId(), oauthParameters);

			GoogleContact contact = gContactDAO.lookup(id);

			if (contact == null) {
				System.out.println("Error: Google contact with id:" + id
						+ " not found.");
				return;
			}

			byte[] imageContent = null;

			try {
				imageContent = contact.getImage();
			} catch (NullPointerException e) {
				System.out
						.println("NullPointerException is throw. Try again with - "
								+ user.getGMailAccessToken()
								+ " : "
								+ user.getGMailAuthSecrete()
								+ " : "
								+ session.getId());
				try {
					imageContent = contact.getImage();
				} catch (NullPointerException e1) {
					System.out
							.println("NullPointerException is throw. Try again with - "
									+ user.getGMailAccessToken()
									+ " : "
									+ user.getGMailAuthSecrete()
									+ " : "
									+ session.getId());
					imageContent = contact.getImage();
				}
			}

			if (imageContent == null) {
				System.out.println("Error: There is no image of id:" + id);
			}

			String imageType = "image/jpeg";

			// returning a picture stored in a byte[] (and its type in
			// imageType)
			response.setContentType(imageType);
			OutputStream out = response.getOutputStream();
			if (imageContent != null) {
				out.write(imageContent);
			}
			out.flush();
			out.close();

		} catch (RollbackException e) {
			e.printStackTrace();
		} catch (MyDAOException e) {
			e.printStackTrace();
		} catch (OAuthException e) {
			e.printStackTrace();
		} catch (ServiceException e) {
			e.printStackTrace();
		} finally {
			System.out.println("Finish GoogleLoadImage.");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
